#encoding utf-8
import os , sys
import plistlib
import platform
try:
	from py_ex import *
except:
	import logging

_opt = "RGBA8888"
_formatType = "cocos2d"
_textureFormat = "png"
_sizeConstaints = "POT"

#check Texturepacker ENV
def chk_tp_env():
	try:
		TEXTURE_HOME = os.environ['TEXTURE_HOME']
	except Exception:
		logging.error ("TEXTURE_HOME not defined. Please define TEXTURE_HOME in your enviroment!")
		return -1 
	return TEXTURE_HOME

#add parent floder naem
def __add_parentname(objvalue , parnetname):
	for k , v in (objvalue["frames"].items()):
		if k.find('/') == -1:
			item = objvalue["frames"].pop(k)
			objvalue["frames"][parnetname + '/' + k] = v	

#del smartupdate 
def __del_smartupdate(objvalue):
	if objvalue["metadata"].get("smartupdate"):
		objvalue["metadata"].pop("smartupdate")

# add floader's name befor single sprite
def __later_proces(floadername , filename , isAddfolder , isDelesmart):
	if os.path.isfile(filename):
		arg = plistlib.readPlist(filename)
		if isAddfolder == True:
			__add_parentname(art , floadername)

		if isDelesmart == True:
			__del_smartupdate(arg)
		plistlib.writePlist(arg , filename)
	

def pack(packdir = os.getcwd() , isdirname = False , rmupdate = False):
	packdir = packdir
	dirname = os.path.split(packdir)[1]

	if packdir == os.getcwd():
		packed_texture = dirname + "." + _textureFormat
		packed_data    = dirname + "." + 'plist'
	else:
		packed_texture = os.path.join(packdir,dirname + "." + _textureFormat) 
		packed_data    = os.path.join(packdir,dirname + "." + 'plist')		

	#Chk Enviorment	 
	chk_tp_env()
	
	#Texture console
	os.system("TexturePacker --sheet " + packed_texture + " --data " + packed_data + " --texture-format " + \
			 _textureFormat + " --format " + _formatType + " --size-constraints " + _sizeConstaints  + " --opt " + \
			 _opt + " --force-publish " + packdir )
	logging.info("Packing the dir [%s] to [%s|%s]" % (packdir , packed_data ,packed_texture))
	__later_proces(dirname , packed_data , isdirname ,rmupdate)	

